package com.chenjun.designpattern.behavior.chain;

/**
 * 职责链模式(Chain of Responsibility)：使多个对象都有机会处理请求，从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链，并沿着这条链传递该请求，直到有一个对象处理它为止。（Avoid coupling the sender of a request to itsreceiver by giving morethan one objecta chance to handle the request.Chain the receiving objects andpassthe request along the chain until an object handles it. ）
1）在职责链模式里，很多对象由每一个对象对其下家的引用而连接起来形成一条链。
2）请求在这条链上传递，直到链上的某一个对象处理此请求为止。
3）发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求，这使得系统可以在不影响客户端的情况下动态地重新组织链和分配责任。
 * @author admin
 *
 */
public class 职责链模式
{

	public static void main(String[] args)
	{
		Request request1 = new HttpRequest();
		Request request2 = new JmsRequest();
		Request request3 = new TcpRequest();

		ConcreteHandler_1 handler1 = new ConcreteHandler_1();
		ConcreteHandler_2 handler2 = new ConcreteHandler_2();
		handler1.setNextandler(handler2);
		
		handler1.handleRequest(request1);
		handler1.handleRequest(request2);
		handler1.handleRequest(request3);
	}

}

interface Handler
{
	public void handleRequest(Request request);
}

interface Request
{
	public void execute();
}

class ConcreteHandler_1 implements Handler
{
	private Handler nextandler;

	@Override
	public void handleRequest(Request request)
	{
		if ( request instanceof HttpRequest )
		{
			new HttpRequest().execute();
		}
		else if ( request instanceof JmsRequest )
		{
			new JmsRequest().execute();
		}
		else
		{
			nextandler.handleRequest(request);
		}
	}

	public Handler getNextandler()
	{
		return nextandler;
	}

	public void setNextandler(Handler nextandler)
	{
		this.nextandler = nextandler;
	}
}

class ConcreteHandler_2 implements Handler
{
	private Handler nextandler;

	@Override
	public void handleRequest(Request request)
	{
		if ( request instanceof HttpRequest )
		{
			new HttpRequest().execute();
		}
		else
		{
			new TcpRequest().execute();
		}
	}

	public Handler getNextandler()
	{
		return nextandler;
	}

	public void setNextandler(Handler nextandler)
	{
		this.nextandler = nextandler;
	}
}

class HttpRequest implements Request
{
	@Override
	public void execute()
	{
		System.out.println("HttpRequest execute");
	}
}

class JmsRequest implements Request
{
	@Override
	public void execute()
	{
		System.out.println("JmsRequest execute");
	}
}

class TcpRequest implements Request
{
	@Override
	public void execute()
	{
		System.out.println("TCP execute");
	}
}
